package logic

import (
	"3kz/models/mysql"
	"3kz/models/redis"
	"3kz/zk3rpc/internal/svc"
	"3kz/zk3rpc/zk3rpc"
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"strconv"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *zk3rpc.ListRequest) (*zk3rpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	var produces []mysql.Produce
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	itoa := strconv.Itoa(int(offset))

	get := redis.Client.Get("list" + itoa)

	if get.Val() == "" {
		mysql.DB.Debug().Limit(int(in.Size)).Offset(int(offset)).Where("product_name like  ?", "%"+in.ProductName+"%").Order("product_price desc").Order("created_at  desc").Find(&produces)
		marshal, _ := json.Marshal(&produces)
		redis.Client.Set("list"+itoa, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &produces)
	}

	fmt.Println(produces)
	var liststruct []*zk3rpc.ListStruct
	for _, product := range produces {
		list := &zk3rpc.ListStruct{
			ProductCode:  product.ProductCode,
			ProductName:  product.ProductName,
			ProductPrice: product.ProductPrice,
			ProductCost:  product.ProductCost,
			Img:          product.Img,
		}
		liststruct = append(liststruct, list)
	}
	return &zk3rpc.ListResponse{List: liststruct}, nil
}
